<template>
  <div class="SpuInfo">
    <el-form
      ref="formRef"
      :class="handleType == 'view' ? 'view' : ''"
      :model="form"
      :rules="rules"
      label-align="right"
      label-width="110"
      size="default"
      inline
      :label-position="handleType == 'view' ? 'left' : 'top'"
    >
      <template v-if="handleType == 'view'">
        <el-row :gutter="21">
          <el-col :span="6">
            <el-form-item label="SPU:">{{ form.spu }}</el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="分类:">{{ form.spu_category_text }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="SPU中文名:">{{ form.spu_cn_title }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="SPU状态:">{{ form.spu_status_text }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="SPU销售状态:">{{
              form.spu_sales_status_text
            }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="SPU货源状态:">{{
              form.spu_supply_status_text
            }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="智能清洁产品状态:" label-width="130">
              {{ is_classified ? form.spu_clean_product_status_text : "--" }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否需要拍照:">
              {{ form.need_photo_text }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否需要加工:">{{
              form.need_processing_text
            }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单位:">{{ getSPUUnit(form.spu_unit) }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="规格型号:">{{ form.specification_model }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品来源:">
              {{ form.goods_source_text }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品物流属性:">{{
              form.logistics_attributes_name
            }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="本地收货仓库:">{{ form.warehouse_name }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="SPU等级:">{{ form.recommended_level }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="品牌类型:">{{ form.brand_type_text }}</el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="品牌备注:">{{ form.imitation_remark }}</el-form-item>
          </el-col>
        </el-row>
      </template>
      <template v-else>
        <div class="w-[100%] flex flex-wrap">
          <el-form-item
            label="分类"
            :required="handleType != 'view'"
            prop="spu_category"
            class="w-500px"
          >
            <template v-if="handleType == 'view'">{{ form.spu_category_text }}</template>
            <template v-else-if="handleType == 'edit'">
              <el-tooltip
                class="item"
                effect="dark"
                :content="form.spu_category_text"
                placement="right"
              >
                <el-input v-model="form.spu_category_text" disabled />
              </el-tooltip>
            </template>
            <template v-else>
              <SelectCategory
                v-model="form.spu_category"
                :showAllLevels="true"
                :clearable="false"
                filterable
                placeholder="产品分类"
                class="w-full"
                @change="changeCategory"
              ></SelectCategory>
            </template>
          </el-form-item>
          <el-form-item
            label="SPU中文名"
            :required="handleType != 'view'"
            prop="spu_cn_title"
            class="w-700px"
          >
            <template v-if="handleType == 'view'">{{ form.spu_cn_title }}</template>
            <template v-else>
              <VGroup class="w-full">
                <el-input
                  class="flex-1 w-320px"
                  v-model="form.spu_cn_title"
                  placeholder="输入"
                  :disabled="disabled"
                />
                <el-button type="primary" @click="modifySkUName" :disabled="disabled"
                  >同步SPU名称到SKU</el-button
                >
              </VGroup>
            </template>
          </el-form-item>
        </div>

        <div class="w-[100%] flex flex-wrap">
          <el-form-item label="SPU" class="w-320px">
            <template v-if="handleType == 'view'"
              ><div>{{ form.spu }}</div></template
            >
            <template v-else
              ><el-input disabled v-model="form.spu" placeholder="SPU"
            /></template>
          </el-form-item>

          <el-form-item label="SPU状态" class="w-130px">
            <template v-if="handleType == 'view'">{{ form.spu_status_text }}</template>
            <template v-else>
              <el-select
                class="w-full"
                v-model="form.spu_status"
                collapse-tags
                placeholder="SPU状态"
                disabled
              >
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].productStatusText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-form-item>

          <el-form-item label="SPU销售状态" class="w-130px">
            <template v-if="handleType == 'view'">
              {{ form.spu_sales_status_text }}
            </template>
            <template v-else>
              <el-select class="w-full" v-model="form.spu_sales_status" disabled>
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].salesStatusText"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </template>
          </el-form-item>

          <el-form-item label="SPU货源状态" class="w-130px">
            <template v-if="handleType == 'view'">
              {{ form.spu_supply_status_text }}
            </template>
            <template v-else>
              <el-select class="w-full" v-model="form.spu_supply_status" disabled>
                <el-option
                  v-for="item in options['goods.GoodsSku']?.[0].supplyStatusText"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </template>
          </el-form-item>

          <el-form-item
            label="智能清洁产品状态"
            v-if="is_classified"
            class="w-160px"
            labelWidth="160px"
          >
            <template #label>
              智能清洁产品状态
              <el-tooltip content="Top center" placement="top">
                <template #content>
                  说明：<br />
                  1、新增SKU，若无变体状态=老品，则状态默认：新品；反之状态默认：老品；
                  <br />
                  2、新品满足连续销售六个月及以上，且无连续一个月（30）无销量情况，状态自动改为：老品；<br />
                  3、新品满足连续销售六个月及以上，且有连续一个月（30）无销量情况，此类修改会自动发起审批；<br />
                  审批通过则变更为老品；审批失败，则改为新品观察期； <br />
                  4、新品观察期，修改为老品；自动发起审批,审批通过则变更为老品；审批失败，则销售状态改为：清库；
                  <br />
                  5、老品状态不支持修改； <br />
                </template>
                <svg-icon icon-class="QuestionFilled"></svg-icon>
              </el-tooltip>
            </template>
            <template v-if="handleType == 'view'">
              {{ form.spu_clean_product_status_text }}
            </template>
            <el-select
              v-else
              class="w-full"
              v-model="form.spu_clean_product_status"
              placeholder="智能清洁产品状态"
              filterable
              disabled
            >
              <el-option
                v-for="item in options['goods.GoodsSku']?.[0].cleanProductStatusText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="w-[100%] flex flex-wrap">
          <el-form-item
            label="是否需要拍照"
            :required="handleType != 'view'"
            class="w-[150px]"
          >
            <template v-if="handleType == 'view'">{{ form.need_photo_text }}</template>
            <template v-else>
              <el-radio-group v-model="form.need_photo" :disabled="disabled">
                <el-radio
                  v-for="item in options['goods.GoodsSpu']?.[0].needPhotoText"
                  :key="item.value"
                  :label="item.value"
                  border
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </template>
          </el-form-item>

          <el-form-item
            label="是否需要加工"
            :required="handleType != 'view'"
            class="w-[150px]"
          >
            <template v-if="handleType == 'view'">
              {{ form.need_processing_text }}</template
            >
            <template v-else>
              <el-radio-group v-model="form.need_processing" :disabled="disabled">
                <el-radio
                  v-for="item in options['goods.GoodsSpu']?.[0].isNeedProcessText"
                  :key="item.value"
                  :label="item.value"
                  border
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </template>
          </el-form-item>
          <el-form-item label="单位" :required="handleType != 'view'">
            <template v-if="handleType == 'view'">{{ form.spu_unit_text }}</template>
            <template v-else>
              <el-select
                class="w-full"
                v-model="form.spu_unit"
                collapse-tags
                placeholder="选择"
                clearable
                :disabled="disabled"
              >
                <el-option
                  v-for="item in options['goods.GoodsSkuSalesInfo']?.[0].spuUnitText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-form-item>

          <el-form-item label="规格型号" :required="handleType != 'view'">
            <template v-if="handleType == 'view'">{{
              form.specification_model
            }}</template>
            <template v-else
              ><el-input
                v-model.trim="form.specification_model"
                placeholder="输入"
                :disabled="disabled"
            /></template>
          </el-form-item>

          <el-form-item label="产品来源">
            <template v-if="handleType == 'view'">{{ form.goods_source_text }}</template>
            <template v-else>
              <el-select
                class="w-full"
                v-model="form.goods_source"
                collapse-tags
                placeholder="选择"
                clearable
                :disabled="disabled"
              >
                <el-option
                  v-for="item in options['goods.GoodsSpu']?.[0].goodsSourceText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-form-item>
        </div>

        <div class="w-[100%] flex flex-wrap">
          <el-form-item
            label="产品物流属性"
            :required="handleType != 'view'"
            prop="logistics_attributes"
          >
            <template v-if="handleType == 'view'">{{
              form.logistics_attributes_name
            }}</template>
            <template v-else>
              <select-logistics
                class="w-full"
                v-model="form.logistics_attributes"
                placeholder="选择"
                @change="changeLogistics"
                @changeItem="changeItemLogistics"
                :disabled="disabled"
              ></select-logistics>
            </template>
          </el-form-item>

          <el-form-item label="品牌类型" class="w-320px">
            <template v-if="handleType == 'view'">
              {{ form.brand_type_text }}:{{ form.imitation_remark }}
            </template>
            <template v-else>
              <VGroup class="w-full">
                <el-select
                  class="!w-[120px]"
                  v-model="form.brand_type"
                  :disabled="disabled"
                >
                  <el-option
                    v-for="item in options['goods.GoodsSpu']?.[0].brandTypeText"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <el-input
                  v-model="form.imitation_remark"
                  placeholder="仿牌备注"
                  :disabled="disabled"
                ></el-input>
              </VGroup>
            </template>
          </el-form-item>

          <el-form-item label="本地收货仓库">
            <template v-if="handleType == 'view'">{{ form.warehouse_name }}</template>
            <template v-else>
              <select-warehouse
                v-model="form.warehouse_id"
                placeholder="仓库"
                class="w-full"
                @change="changeWarehouse"
                :disabled="disabled"
              ></select-warehouse>
            </template>
          </el-form-item>

          <el-form-item label="SPU等级" class="w-120px">
            <template v-if="handleType == 'view'">{{ form.recommended_level }}</template>
            <template v-else>
              <el-select
                class="w-full"
                v-model="form.recommended_level"
                collapse-tags
                placeholder="选择"
                clearable
                disabled
              >
                <el-option
                  v-for="item in options['goods.GoodsSpu']?.[0].recommendLevelText"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                /> </el-select
            ></template>
          </el-form-item>
        </div>
      </template>
    </el-form>
  </div>
</template>

<script setup name="SpuInfo">
import { reactive, inject } from "vue";
import SelectCategory from "@/components/SelectCategory";
import SelectLogistics from "@/components/SelectLogistics";
import SelectWarehouse from "@/components/SelectWarehouse";
import { getSpu } from "../api";
import { ElMessage } from "element-plus";
import { scrollToError } from "@/hooks/formScroll.js";
import { clean_classified } from "@/utils/product/data.js";

let options = reactive(inject("options"));
let handleType = reactive(inject("handleType"));
let formData = reactive(inject("form"));
const emits = defineEmits(["update:modelValue", "initsku", "sync"]);

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

// 是否智能清洁产品
const is_classified = ref(false);

const form = computed({
  get: () => props.modelValue,
  set: (val) => {
    emit("update:modelValue", val);
  },
});

watch(
  formData,
  (newVal, oldVal) => {
    is_classified.value = clean_classified.includes(
      newVal.spu_category ? newVal.spu_category[0] : ""
    );
  },
  { deep: true }
);

const disabled = computed(() => {
  return (
    handleType.value == "view" ||
    (handleType.value == "edit" &&
      !(window.BTN_AUTH || []).includes("/goods/task/product/spu-info"))
  );
});

const rules = reactive({
  spu_category: [{ required: true, message: "请选择产品分类", trigger: "change" }],
  spu_cn_title: [{ required: true, message: "请输入产品中文名称", trigger: "change" }],
  logistics_attributes: [
    { required: true, message: "请选择产品物流属性", trigger: "change" },
  ],
});
const changeCategory = async () => {
  try {
    const res = await getSpu({
      spu: "",
      productCategory: form.value.spu_category,
      attributes: [],
    });
    if (res.data) {
      form.value.spu = res.data.spu;
      emits("initsku");
    }
  } catch (e) {
    throw Error(e);
  }
};

const changeWarehouse = (val) => {
  form.value.warehouse_name = val;
};

const changeLogistics = (val) => {
  form.value.logistics_attributes_name = val;
};

const changeItemLogistics = (item) => {
  form.value.is_dangerous = item?.is_dangerous;
};

const modifySkUName = () => {
  if (!form.value.spu_cn_title) {
    ElMessage.error("请输入产品中文名称");
    return;
  }
  if (form.value.goods_sku.length == 0) {
    ElMessage.error("请检查是否存在SKU信息");
    return;
  }
  form.value.goods_sku.forEach((i) => {
    i.sku_cn_title = form.value.spu_cn_title;
    i.goods_sku_title = i.goods_sku_title.map((j) => {
      if (j.language_id == 1) {
        j.title = form.value.spu_cn_title;
      }
      return j;
    });
  });
  ElMessage.success("修改成功");
  emits("sync");
};

const formRef = ref();

//表单校验
const validate = () => {
  return new Promise((resolve, reject) => {
    formRef.value?.validate((valid, fields) => {
      if (valid) {
        resolve(true);
      } else {
        scrollToError(document.querySelector(".is-error"));
        reject(false);
      }
    });
  });
};

const getSPUUnit = (val) => {
  return options.value["goods.GoodsSkuSalesInfo"]?.[0].spuUnitText.find(
    (i) => i.value == val
  )?.label;
};

defineExpose({ changeCategory, validate });
</script>

<style lang="scss" scoped>
.view {
  .el-form-item {
    width: 100% !important;
  }
  .flex-wrap {
    display: grid !important;
    grid-template-columns: repeat(4, minmax(0, 1fr)) !important;
  }

  :deep(.el-form-item__label) {
    color: #999999;
    font-weight: 400;
  }
}
.el-form-item {
  width: 200px;
  &.w-120px {
    width: 120px;
  }
  &.w-140px {
    width: 140px;
  }
  &.w-320px {
    width: 320px;
  }
  &.w-700px {
    width: 700px;
  }
  &.w-35vw {
    width: 35vw;
  }
  &.w-500px {
    width: 500px;
  }
}
</style>
